import React, { Component } from 'react'
import { StatusBar, Linking, ActivityIndicator, Alert, BackHandler, Modal, TouchableOpacity, View, ScrollView, Text, KeyboardAvoidingView } from 'react-native'
import { connect } from 'react-redux'
import { Button } from '../Components'

import AppConfig from '../Config/AppConfig'
const domain = AppConfig.domain

import Alipay from '../Lib/Alipay'
import * as WeChat from 'react-native-wechat'

// Styles
import styles from './Styles/RechargeScreenStyle'

class RechargeScreen extends Component {
  static navigationOptions = {
    title: '充值'
  }
  constructor(props) {
    super(props)
    const dataList = [100,500,2000,10000]
    this.state = {
      loading: false,
      fetching: false,
      payType: null,
      dataList: dataList,
      orderInfo: null,
      money: dataList[0],
      modalVisible: false,
    }
  }
  componentDidMount() {
    Linking.addEventListener('url', this._handleOpenURL);
    BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
  }
  componentWillUnmount() {
    Linking.removeEventListener('url', this._handleOpenURL);
    BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
  }
  componentDidUpdate(prevProps, prevState) {
    if(prevState.fetching
      && !this.state.fetching) {
      //this.setState({loading:false})
      if(this.state.payType == 'alipay') {
        this.doAlipay()
      } else {
        this.doWxpay()
      }
    }
  }
  _handleOpenURL(event) {
    console.log(event.url)
    if (event.url.search(/9000/) > 0) {
      Alert.alert('支付成功')
    } else {
      Alert.alert('支付失败')
    }
  }
  onBackPress = () => {
    this.props.navigation.goBack()
    return true
  }
  doAlipay() {
    const orderInfo = this.state.orderInfo
    Alipay.pay(orderInfo).then((result) => {
      console.tron.log(result)
      if(result.resultStatus == '9000') {
        Alert.alert('提示','充值成功')
      }
    }).catch((error) => console.error(error))
  }
  doWxpay() {
    const orderInfo = this.state.orderInfo
    console.log(orderInfo)
    WeChat.pay(orderInfo).then((result) => {
      if(result.errCode == '0') {
        Alert.alert('提示','支付成功')
      }
    }).catch((error) => console.error(error))
  }
  getOrderInfo(payType) {
    this.setState({
      //loading: true,
      modalVisible: false,
      fetching:true,
      payType: payType
    })
    let url = domain+'/api/payment/get_code'
    return fetch(url, {
      method: 'POST',
      headers: {
        //'Accept': 'application/json',
        'Content-Type': 'application/json',
        'token': this.props.token,
      },
      body: JSON.stringify({
        pay_radio: payType,
        amount: this.state.money,
      })
    })
      .then((response) => {
        if(payType == 'alipay') {
          return response.text()
        } else {
          return response.json()
        }
      })
      .then((responseJson) => {
        console.tron.log(responseJson)
        this.setState({
          fetching: false,
          orderInfo: responseJson
        })
      })
      .catch((error) => console.error(error))
  }
  render () {
    return (
      <ScrollView style={styles.container}>
        <StatusBar translucent={false} barStyle='dark-content' />
        <Modal
          onRequestClose={()=>null}
          transparent={true}
          visible={this.state.loading}>
          <View style={{flex:1,backgroundColor:'rgba(0,0,0,0.6)',justifyContent:'center'}}>
            <ActivityIndicator color='rgba(255,255,255,0.8)' size='large' />
          </View>
        </Modal>
        <KeyboardAvoidingView behavior='position'>
          <Text style={styles.title}>金额:</Text>
          <View style={styles.box}>
            {this.state.dataList.map((item, index) =>
              <View style={styles.item} key={index}>
                {this.state.money == item ? (
                  <View key={index} style={styles.boxItemActive}>
                    <Text style={styles.itemTextActive}>{item}</Text>
                  </View>
                ) : (
                  <TouchableOpacity
                    onPress={()=>this.setState({money:item})}
                    style={styles.boxItem}>
                    <Text style={styles.itemText}>{item}</Text>
                  </TouchableOpacity>
                )}
              </View>
            )}
          </View>
          <Button title='充值'
            style={{padding:12}}
            onPress={()=>this.setState({modalVisible:true})} />
        </KeyboardAvoidingView>
        <Modal
          onRequestClose={()=>null}
          visible={this.state.modalVisible}
          transparent={true}>
          <TouchableOpacity
            onPress={()=>this.setState({modalVisible:false})}
            style={styles.modalBg}></TouchableOpacity>
          <View style={styles.modalContainer}>
            <Button margin title='支付宝'
              onPress={()=>this.getOrderInfo('alipay')} />
            <Button title='微信'
              onPress={()=>this.getOrderInfo('wxpay')}
            />
          </View>
        </Modal>
      </ScrollView>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    token: state.user.payload.token
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(RechargeScreen)
